//
//  LocationManager.swift
//  testZD
//
//  Created by 湛亚磊 on 2020/9/19.
//  Copyright © 2020 湛亚磊. All rights reserved.
//

import UIKit
///定位
///高德处理定位
import CoreLocation
public typealias MKPositioningClosure = (String) -> ()

open class LocationManager: NSObject {

    ///全部信息
    public var clousre : MKPositioningClosure?
    private var locationManager : CLLocationManager?
    private weak var viewController : UINavigationController?      // 承接外部传过来的视图控制器，做弹框处理
    // 外部初始化的对象调用，执行定位处理。
    public func startPositioning(_ vc:UINavigationController?) {
        viewController = vc
        if (self.locationManager != nil) && (CLLocationManager.authorizationStatus() == .denied) {
            // 定位提示
            if viewController != nil{
                alter(viewController: viewController!)
            }
        } else {
            requestLocationServicesAuthorization()
        }
    }
    
    
    // 初始化定位
    private func requestLocationServicesAuthorization() {
        
        if (self.locationManager == nil) {
            self.locationManager = CLLocationManager()
            self.locationManager?.delegate = self
        }
        
        self.locationManager?.requestWhenInUseAuthorization()
        self.locationManager?.startUpdatingLocation()
        
        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.notDetermined) {
            locationManager?.requestWhenInUseAuthorization()
        }
        
        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse) {
            locationManager?.desiredAccuracy = kCLLocationAccuracyBest
            let distance : CLLocationDistance = 10.0
            locationManager?.distanceFilter = distance
            locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager?.startUpdatingLocation()
        }
    }
    
    
    // 获取定位代理返回状态进行处理
    private func reportLocationServicesAuthorizationStatus(status:CLAuthorizationStatus) {
        if status == .notDetermined {
            // 未决定,继续请求授权
            requestLocationServicesAuthorization()
        } else if (status == .restricted) {
            // 受限制，尝试提示然后进入设置页面进行处理
            if viewController != nil{
                alter(viewController: viewController!)
            }
        } else if (status == .denied) {
            // 受限制，尝试提示然后进入设置页面进行处理
            if viewController != nil{
                alter(viewController: viewController!)
            }
            
        }
    }
    
    
    private func alter(viewController:UINavigationController) {
        ///未开启权限的处理
        let alert = UIAlertController(title: "定位服务未开启", message: "请在系统设置中开启定位服务", preferredStyle: .alert)
        let cancleAction = UIAlertAction(title: "暂不", style: .cancel, handler: { (action) in
            viewController.popViewController(animated: true)
            
        })
        let shureAction = UIAlertAction(title: "去设置", style: .default, handler: { (action) in
            let url=URL(string: UIApplication.openSettingsURLString)
            if UIApplication.shared.canOpenURL(url!){
                UIApplication.shared.open(url!, options: [:], completionHandler: nil)
                UIApplication.shared.open(url!, options: [:], completionHandler: { (flag) in
                    print("设置的定位的回调----》》》》")
                })
            }
            
        })
        
        alert.addAction(cancleAction)
        alert.addAction(shureAction)
        viewController.present(alert, animated: true, completion: nil)
    }
}

extension LocationManager:  CLLocationManagerDelegate {
    
    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        self.locationManager?.stopUpdatingLocation()
        
        let location = locations.last ?? CLLocation()
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
            
            if error != nil {
                if self.clousre != nil {
                    self.clousre!("失败")
                }
                return
            }
            
            if let place = placemarks?[0]{
                
                // 国家 省  市  区  街道  名称  国家编码  邮编
                //                let country = place.country ?? ""
                let administrativeArea = place.administrativeArea ?? ""
                let locality = place.locality ?? ""
                let subLocality = place.subLocality ?? ""
                //let thoroughfare = place.thoroughfare ?? ""
                //let name = place.name ?? ""
                
                //                let isoCountryCode = place.isoCountryCode ?? ""
                //                let postalCode = place.postalCode ?? ""
                print("\(administrativeArea) --- >>\(locality) -->>>\(subLocality)")
                self.clousre?(administrativeArea)
                
            } else {
                
                if self.clousre != nil {
                    self.clousre!("No placemarks!")
                }
            }
        }
    }
    
    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        reportLocationServicesAuthorizationStatus(status: status)
    }
    
    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        self.locationManager?.stopUpdatingLocation()
    }
}
